/**
 * viewerService.js
 * 提供医学影像浏览器的核心加载功能
 * 从ViewerPage.vue中提取，用于管理患者、研究和序列的加载逻辑
 */

import orthancService from '@/services/orthanc';
import cornerstone from 'cornerstone-core';
import * as imageService from '@/services/imageService';
import * as metadataService from '@/services/metadataService';

/**
 * 加载患者的所有检查
 * @param {string} patientId - 患者ID
 * @returns {Promise<Object>} - 包含检查列表和活动检查ID的对象
 */
export async function loadPatientStudies(patientId) {
  try {
    console.log('加载患者的所有检查:', patientId);
    
    // 获取患者的所有检查
    const studies = await orthancService.getPatientStudies(patientId);
    
    if (studies && studies.length > 0) {
      // 按检查日期排序，最新的排在前面
      const sortedStudies = studies.sort((a, b) => {
        const dateA = a.MainDicomTags.StudyDate || '19000101';
        const dateB = b.MainDicomTags.StudyDate || '19000101';
        return dateB.localeCompare(dateA); // 降序排列
      });
      
      console.log('患者检查列表:', sortedStudies);
      
      // 默认选择最新的检查
      const activeStudyId = sortedStudies[0].ID;
      
      return {
        success: true,
        studyList: sortedStudies,
        activeStudyId
      };
    } else {
      console.error('未找到患者检查');
      return {
        success: false,
        error: '未找到患者检查',
        studyList: [],
        activeStudyId: null
      };
    }
  } catch (error) {
    console.error('加载患者检查失败:', error);
    return {
      success: false,
      error: error.message || '加载患者检查失败',
      studyList: [],
      activeStudyId: null
    };
  }
}

/**
 * 加载指定检查的所有序列
 * @param {string} studyId - 检查ID
 * @returns {Promise<Object>} - 包含序列列表和活动序列ID的对象
 */
export async function loadStudy(studyId) {
  try {
    console.log('加载检查:', studyId);
    
    // 获取检查的所有序列
    const series = await orthancService.getStudySeries(studyId);
    
    if (series && series.length > 0) {
      // 处理序列数据
      const seriesList = series.map(s => ({
        id: s.ID,
        description: s.MainDicomTags.SeriesDescription || '未命名序列',
        number: s.MainDicomTags.SeriesNumber || '0',
        modality: s.MainDicomTags.Modality || 'Unknown',
        instances: s.Instances || [],
        thumbnailUrl: null,
        loading: false,
        loadProgress: 0
      }));
      
      console.log('检查序列列表:', seriesList);
      
      // 默认选择第一个序列
      const activeSeries = seriesList[0].id;
      
      return {
        success: true,
        seriesList,
        activeSeries
      };
    } else {
      console.error('未找到检查序列');
      return {
        success: false,
        error: '未找到检查序列',
        seriesList: [],
        activeSeries: null
      };
    }
  } catch (error) {
    console.error('加载检查失败:', error);
    return {
      success: false,
      error: error.message || '加载检查失败',
      seriesList: [],
      activeSeries: null
    };
  }
}

/**
 * 加载序列的所有实例
 * @param {string} seriesId - 序列ID
 * @param {Object} series - 序列对象，用于更新加载状态
 * @returns {Promise<Object>} - 包含图像ID列表和序列描述的对象
 */
export async function loadSeries(seriesId, series) {
  try {
    console.log('加载序列', seriesId);
    
    // 清空图像ID列表
    const imageIds = [];
    
    // 获取序列描述
    const seriesDescription = series ? (series.description || seriesId) : seriesId;
    
    // 检查是否已经有实例数据
    let instances = [];
    if (series && series.instances && series.instances.length > 0) {
      console.log('使用已缓存的实例数据');
      instances = series.instances;
    } else {
      // 获取序列的实例
      instances = await orthancService.getInstancesForSeries(seriesId);
      
      // 更新序列的实例缓存
      if (series) {
        series.instances = instances;
      }
    }
    
    if (!instances || instances.length === 0) {
      throw new Error('未找到实例');
    }
    
    // 设置图像ID列表
    const imageIdsList = instances.map(instance => {
      const instanceId = instance.ID || instance.id || instance;
      return `wadouri:/api/instances/${instanceId}/file`;
    });
    
    return {
      success: true,
      imageIds: imageIdsList,
      totalImages: imageIdsList.length,
      currentSeriesDescription: seriesDescription
    };
  } catch (error) {
    console.error('加载序列失败:', error);
    return {
      success: false,
      error: error.message || '加载序列失败',
      imageIds: [],
      totalImages: 0,
      currentSeriesDescription: ''
    };
  }
}

/**
 * 加载并显示图像
 * @param {string} imageId - 图像ID
 * @param {HTMLElement} viewportElement - 显示图像的DOM元素
 * @returns {Promise<Object>} - 加载的图像
 */
export async function loadAndDisplayImage(imageId, viewportElement) {
  if (!imageId) return null;
  
  try {
    console.log('加载图像', imageId);
    const startTime = performance.now();
    
    // 检查图像是否已经缓存
    if (!cornerstone.imageCache.cachedImages[imageId]) {
      // 如果图像未缓存，先显示加载状态但不清除当前图像
      // 在这里不设置状态，由调用者处理
    }
    
    // 加载图像
    const image = await cornerstone.loadAndCacheImage(imageId);
    
    // 显示图像 (如果提供了viewportElement)
    if (viewportElement) {
      cornerstone.displayImage(viewportElement, image);
    }
    
    // 记录加载时间
    const loadTime = performance.now() - startTime;
    console.log(`图像 ${imageId} 加载并显示完成，耗时: ${loadTime.toFixed(2)}ms`);
    
    return image;
  } catch (error) {
    console.error('加载图像失败:', error);
    return null;
  }
}

/**
 * 带进度条的预加载
 * @param {Array<string>} imageIds - 图像ID数组
 * @param {Object} series - 序列对象，用于更新加载进度
 * @returns {Promise<void>}
 */
export function preloadImagesWithProgress(imageIds, series) {
  return imageService.preloadImagesWithProgress(imageIds, series);
}

/**
 * 为序列创建缩略图
 * @param {Object} series - 序列对象
 * @param {Object} image - cornerstone图像对象
 * @returns {boolean} 成功返回true
 */
export function createThumbnail(series, image) {
  if (!series || !image) {
    console.error('创建缩略图失败: 无效的序列或图像');
    return false;
  }
  
  try {
    // 创建缩略图
    const canvas = document.createElement('canvas');
    canvas.width = 60;
    canvas.height = 60;
    const ctx = canvas.getContext('2d');
    
    // 填充黑色背景
    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 直接从cornerstone获取canvas
    const imageCanvas = image.getCanvas();
    if (!imageCanvas) {
      throw new Error('无法获取图像canvas');
    }
    
    // 计算缩放比例和位置
    const srcWidth = imageCanvas.width;
    const srcHeight = imageCanvas.height;
    const scale = Math.min(canvas.width / srcWidth, canvas.height / srcHeight);
    const destWidth = srcWidth * scale;
    const destHeight = srcHeight * scale;
    const x = (canvas.width - destWidth) / 2;
    const y = (canvas.height - destHeight) / 2;
    
    // 绘制图像到缩略图canvas
    ctx.drawImage(imageCanvas, 0, 0, srcWidth, srcHeight, x, y, destWidth, destHeight);
    
    // 添加边框
    ctx.strokeStyle = '#444';
    ctx.lineWidth = 1;
    ctx.strokeRect(0, 0, canvas.width, canvas.height);
    
    // 创建缩略图URL
    try {
      const thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8);
      series.thumbnailUrl = thumbnailUrl;
      series.hasThumbnail = true;
      
      console.log(`成功为序列 ${series.id} (${series.modality}) 创建缩略图`);
      return true;
    } catch (error) {
      console.error('创建缩略图URL失败:', error);
      createPlaceholderThumbnail(ctx, series);
      return false;
    }
  } catch (error) {
    console.error('创建缩略图失败:', error);
    // 创建后备缩略图
    const canvas = document.createElement('canvas');
    canvas.width = 60;
    canvas.height = 60;
    createPlaceholderThumbnail(canvas.getContext('2d'), series);
    
    try {
      const thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8);
      series.thumbnailUrl = thumbnailUrl;
    } catch (e) {
      console.error('创建后备缩略图失败:', e);
    }
    
    return false;
  }
}

/**
 * 预加载相邻图像
 * @param {number} currentIndex - 当前图像索引
 * @param {Array<string>} imageIds - 所有图像ID数组
 */
export function preloadAdjacentImages(currentIndex, imageIds) {
  return imageService.preloadAdjacentImages(currentIndex, imageIds);
}

/**
 * 更新图像元数据
 * @param {number} index - 图像索引
 * @param {Array<string>} imageIds - 图像ID数组
 * @param {HTMLElement} viewportElement - 视口元素
 * @returns {Object|null} - 图像元数据
 */
export function updateImageMetadata(index, imageIds, viewportElement) {
  return metadataService.updateImageMetadata(index, imageIds, viewportElement);
}

/**
 * 创建占位缩略图
 * @param {CanvasRenderingContext2D} ctx - Canvas上下文
 * @param {Object} series - 序列对象
 */
export function createPlaceholderThumbnail(ctx, series) {
  // 填充背景
  ctx.fillStyle = '#2a2a2a';
  ctx.fillRect(0, 0, 60, 60);
  
  // 绘制边框
  ctx.strokeStyle = '#444';
  ctx.lineWidth = 2;
  ctx.strokeRect(2, 2, 56, 56);
  
  // 绘制模态信息
  ctx.fillStyle = '#409EFF';
  ctx.font = '14px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(series.modality || 'IMG', 30, 30);
  
  // 绘制序列编号
  if (series.number) {
    ctx.font = '10px Arial';
    ctx.fillText(`#${series.number}`, 30, 45);
  }
} 